package 多线程高并发.创建并启动线程;

import java.util.concurrent.Executors;

//
public class chuangjianxiancheng {
    //创建线程一般是有两种方式
    // 1.继承Thread；new MyThread().start();
    // 2.实现接口Runnable；new Thread(new MyRun()).start();必须new Thread（）然后再里面创建
    //两种方法都需要的就是重写run（）方法
    static class MyThread extends Thread{
        @Override
        public void run() {
            for(int i=0;i<100;i++)
            { System.out.println(i);
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("hello MyThread");
        }
    }
    static class MyRun implements Runnable{
        @Override
        public void run() {
            for(int i=101;i<200;i++)
            { System.out.println(i);
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("Hello MyRun");
        }
    }

    public static void main(String[] args) {
        //readFromDataBase();//两个都是单独的执行自己的程序，
        //WriteDataToFile();//不会同步交叉的执行
        //如果说才用的发昂法是.run()不会重新开启一个线程，而是会去执行run方法，执行完成后在接着执行后续程序
        Thread t=new MyThread();
        System.out.println(t.getState());
       // new MyThread().start();
        t.start();
        System.out.println(t.getState());
        //new Thread(new MyRun()).start();
        new Thread(()->{//lambda表达式方式
            System.out.println("hello lambda");
        }).start();


    }

    private static void readFromDataBase(){
        try {
            println("Begin read data from db.");
            Thread.sleep(1000*10l);
            println("Read data done and start handle it.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        println("The data handle finish and successfully");
    }

    private static void WriteDataToFile(){
        try {
            println("Begin write data from db.");
            Thread.sleep(2000*10l);
            println("Write data done and start handle it.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        println("The data handle finish and successfully");

    }
    private static void println(String message){
        System.out.println(message);
    }
}
